package com.cms.controller.front;

import java.math.BigDecimal;
import java.util.Date;

import com.cms.entity.Money;
import com.cms.enums.VIPEnums;
import com.cms.util.ShorUrlUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;

import com.cms.Feedback;
import com.cms.entity.Member;
import com.cms.routes.RouteMapping;

/**
 * Controller - 注册
 *
 *
 *
 */
@RouteMapping(url = "/register")
public class RegisterController extends BaseController{

	/**
	 * 注册页面
	 */
	public void index(){
	    String username = getPara("username");
        String password = getPara("password");
        String inviteCode=getPara("inviteCode");
        String weixinOpenId=getPara("weixinOpenId");
        if(StringUtils.isNotBlank(username) ){
        	Member pMember = new Member().dao().findByUsername(username);
        	if(pMember!=null){
        		setAttr("feedback", Feedback.error("用户已存在"));
        		render("/templates/"+getTheme()+"/"+getDevice()+"/register.html");
        	}else{
        		Member member = new Member();
        		member.setMobile(username);
        		member.setPassword(DigestUtils.md5Hex(password));
        		member.setAmount(BigDecimal.ZERO);
        		member.setBalance(BigDecimal.ZERO);
        		member.setRegisterIp(getRequest().getRemoteAddr());
        		member.setCreateDate(new Date());
        		member.setModifyDate(new Date());
        		member.setWeixinOpenId(weixinOpenId);
				member.setInviteCode( ShorUrlUtil.shortUrl(username)[0]);
				member.setVipLevel(VIPEnums.V0.getKey());
				member.setAchievement(BigDecimal.ZERO);
				if(StringUtils.isNotBlank(inviteCode)){
					Member parentMember = new Member().dao().findByInviteCode(inviteCode);
					if(parentMember!=null){
						member.setParentId(parentMember.getId());
					}
				}
				member.setTjCount(0);
        		member.save();
        		//初始化资金信息
        		new Money().initMoney(member);
				getSession().setAttribute(Member.SESSION_MEMBER, member);
        		redirect("/");
        	}
        }else{
            render("/templates/"+getTheme()+"/"+getDevice()+"/register.html");
        }
	}
}
